//
//  ChangeViewController.m
//  DaiShengInvest
//
//  Created by 张睿 on 2017/7/5.
//  Copyright © 2017年 davinci. All rights reserved.
//

#import "ChangeViewController.h"
#import "OrderViewController.h"

@interface ChangeViewController ()<UITextFieldDelegate>

@property (nonatomic, weak)UIImageView * backImageView;

@property (nonatomic, strong)UITableView * tableView;

@property (nonatomic, strong)UIView * lineView;

@property (nonatomic, strong)UIButton * sureButton;

@property (nonatomic, strong)UILabel * pendingLabel;
@property (nonatomic, strong)UITextField * pendingTextField;
@property (nonatomic, strong)UILabel * stopWinLabel;
@property (nonatomic, strong)UITextField * stopWinTextField;

@end

@implementation ChangeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupNavBar];
    [self setupUI];
}

- (void)setupNavBar{
    
    self.title = @"设置止盈止损";
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(15 * SCREENH6, 5 * SCREENH6, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"1返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToAccountView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
}



- (void)setupUI{
    
//    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    UIImageView * backImage = [[UIImageView alloc] init];
    
    backImage.image = [UIImage imageNamed:@"背景"];
    
    self.backImageView = backImage;
    
    [self.view addSubview:self.backImageView];
    
    
    
    self.pendingLabel = [self setupLabel:@"止损点数"];
    
    [self.view addSubview:self.pendingLabel];
    
    self.pendingTextField = [self setupTextField:@"价格"];
    
    [self.view addSubview:self.pendingTextField];
    
    self.stopWinLabel = [self setupLabel:@"止盈点数"];
    
    [self.view addSubview:self.stopWinLabel];
    
    self.stopWinTextField = [self setupTextField:@"价格"];
    
    [self.view addSubview:self.stopWinTextField];
    
    
    self.lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 260 * SCREENH6, SCREEN_WIDTH, 1 * SCREENH6)];
    
    self.lineView.backgroundColor = [UIColor whiteColor];
    self.lineView.alpha = 0.1;
    
    [self.view addSubview:self.lineView];
    
    
    self.sureButton = [[UIButton alloc] initWithFrame:CGRectMake(15 * SCREENH6, 470 * SCREENH6, 345 * SCREENH6, 50 * SCREENH6)];
    
    [self.sureButton setTitle:@"确认修改" forState:UIControlStateNormal];
    self.sureButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:15 * SCREENH6];//
    [self.sureButton setBackgroundImage:[UIImage imageNamed:@"注册"] forState:UIControlStateNormal];
    self.sureButton.layer.borderColor = [[UIColor blackColor] CGColor];
    //边框宽度
    //    saveButton.layer.borderWidth =1.0f;
    //处理圆角
    self.sureButton.layer.cornerRadius =5.0f;
    [self.sureButton setTitleColor:ColorWithRGB(0xffffff) forState:UIControlStateNormal];
    [self.sureButton addTarget:self action:@selector(didChangeButton) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.sureButton];
}



- (void)viewDidLayoutSubviews{
    
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.mas_equalTo(self.view);
    }];
    
    
    [self.pendingLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(15 * SCREENH6);
        make.top.mas_equalTo(self.view).offset(100 * SCREENH6);
    }];
    
    
    [self.pendingTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(90 * SCREENH6);
        make.centerY.mas_equalTo(self.pendingLabel);
        make.trailing.mas_equalTo(self.view).offset(-15 * SCREENH6);
        make.height.mas_equalTo(40 * SCREENH6);
    }];
    
    [self.stopWinTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.pendingTextField.mas_bottom).offset(40 * SCREENH6);
        make.leading.trailing.height.mas_equalTo(self.pendingTextField);
    }];
    
    [self.stopWinLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.pendingLabel);
        make.centerY.mas_equalTo(self.stopWinTextField);
    }];
}


- (UILabel *)setupLabel:(NSString *)string{
    
    UILabel * label = [UILabel new];
    
    label.font = [UIFont fontWithName:@"PingFangSC-Medium" size:15 * SCREENH6];
    label.textColor = ColorWithRGB(0xffffff);
    label.text = string;
    
    return label;
}


- (UITextField *)setupTextField:(NSString *)name{    
    
    UITextField * textFiled = [[UITextField alloc] init];
    
    textFiled.borderStyle = UITextBorderStyleNone;
    textFiled.backgroundColor = [UIColor clearColor];
    
    textFiled.background = [UIImage imageNamed:name];
    textFiled.textAlignment = UITextAlignmentCenter;
    
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = ColorWithRGB(0xa2a2a2);
    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"未设置" attributes:attrs];
    textFiled.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    textFiled.textColor = ColorWithRGB(0xeeeeee);
//    textFiled.text = @"10";
    textFiled.delegate = self;
    
    UIButton * reduceButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40 * SCREENH6, 40 * SCREENH6)];
    
    reduceButton.backgroundColor = [UIColor clearColor];
    [reduceButton addTarget:self action:@selector(didReduceButton:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [textFiled addSubview:reduceButton];
    
    textFiled.leftView = reduceButton;
    textFiled.leftViewMode = UITextFieldViewModeAlways;
    
    
    UIButton * addButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40 * SCREENH6, 40 * SCREENH6)];
    
    addButton.backgroundColor = [UIColor clearColor];
    [addButton addTarget:self action:@selector(didAddButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [textFiled addSubview:addButton];
    
    textFiled.rightView = addButton;
    textFiled.rightViewMode = UITextFieldViewModeAlways;
    
    textFiled.keyboardType = UIKeyboardTypeNumberPad;
    textFiled.keyboardAppearance = UIKeyboardAppearanceDark;
    
    
    return textFiled;
}


//点击确认按钮
- (void)didChangeButton{
    
    float price = [self.pirceString floatValue];
    
    float stopLoseFloat = 0.0000;
    float stopWinFloat = 0.0000;
    
    if ([self.stopWinTextField.text isEqualToString:@""] && [self.pendingTextField.text isEqualToString:@""]) {
        
    }else if ([self.stopWinTextField.text isEqualToString:@""]){
        
        int stopLose = [self.pendingTextField.text intValue];
        
        NSArray * bidArray = [self.pirceString componentsSeparatedByString:@"."];
        
        NSString * firstBid = bidArray.firstObject;
        
        NSInteger  bidLength = [firstBid length];
        double stopLossa = pow(0.1, 5 - bidLength) * stopLose;
        
        if ([self.typeString isEqualToString:@"Buy"]) {
            
            stopLoseFloat = price - stopLossa;
        }else{
            stopLoseFloat = price + stopLossa;
            
        }}else if ([self.pendingTextField.text isEqualToString:@""]){
            
            int stopLose = [self.stopWinTextField.text intValue];
            
            NSArray * bidArray = [self.pirceString componentsSeparatedByString:@"."];
            
            NSString * firstBid = bidArray.firstObject;
            
            NSInteger  bidLength = [firstBid length];
            double stopLossa = pow(0.1, 5 - bidLength) * stopLose;
            
            if ([self.typeString isEqualToString:@"Buy"]) {
                
                stopWinFloat = price + stopLossa;
                
            }else{
                stopWinFloat = price - stopLossa;
                
            }
        }else {
            
            int stopLoss = [self.pendingTextField.text intValue];
            int stopWin = [self.stopWinTextField.text intValue];
            
            NSArray * bidArray = [self.pirceString componentsSeparatedByString:@"."];
            
            NSString * firstBid = bidArray.firstObject;
            
            NSInteger  bidLength = [firstBid length];
            
            double stopLossa = pow(0.1, 5 -bidLength) * stopLoss;
            double stopWina = pow(0.1, 5 - bidLength) * stopWin;
            
            if ([self.typeString isEqualToString:@"Buy"]) {
                
                stopLoseFloat = price - stopLossa;
                stopWinFloat = price + stopWina;
            }else{
                
                stopLoseFloat = price + stopLossa;
                stopWinFloat = price - stopWina;
            }
        }
    
    
    NSString * stopLoseStr = [NSString stringWithFormat:@"%f",stopLoseFloat];
    NSString * stopWinStr = [NSString stringWithFormat:@"%f",stopWinFloat];
    
    
    NSLog(@"======stopLoseStr %@",stopLoseStr);
    NSLog(@"======stopWinStr %@",stopWinStr);
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    if ([self.type isEqualToString:@"2"]) {
        
        NSDictionary * parameters = @{@"positionId":self.positionId,@"stopLoss":stopLoseStr,@"takeProfit":stopWinStr};
        
        [[NetworkTool sharedTools] POST:@"symbols/edit-positions" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            NSString * code = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
            
            if ([code isEqualToString:@"0"]) {
                
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:@"恭喜你，修改成功！"
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          //响应事件
//                                                                          [self.navigationController popViewControllerAnimated:YES];

                                                                          for (UIViewController *controller in self.navigationController.viewControllers) {
                                                                              if ([controller isKindOfClass:[OrderViewController class]]) {
                                                                                  OrderViewController *revise =(OrderViewController *)controller;
                                                                                  [self.navigationController popToViewController:revise animated:YES];  
                                                                              }  
                                                                          }
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseObject[@"msg"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          //响应事件
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"服务器内部错误，请稍后再试。"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }];
    }else if ([self.type isEqualToString:@"1"]){
        
//        NSLog(@"==%@",self.positionId);
        
        NSDictionary * parameters = @{@"orderId":self.positionId,@"stopLoss":stopLoseStr,@"takeProfit":stopWinStr,@"orderPrice":self.pirceString};
        
        [[NetworkTool sharedTools] POST:@"symbols/edit-orders" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            NSString * code = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
            
            if ([code isEqualToString:@"0"]) {
                
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:@"恭喜你，修改成功！"
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          //响应事件
                                                                          for (UIViewController *controller in self.navigationController.viewControllers) {
                                                                              if ([controller isKindOfClass:[OrderViewController class]]) {
                                                                                  OrderViewController *revise =(OrderViewController *)controller;
                                                                                  [self.navigationController popToViewController:revise animated:YES];
                                                                              }
                                                                          }
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseObject[@"msg"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          //响应事件
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"服务器内部错误，请稍后再试。"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }];
        
    }
    
   
}



//点击减少按钮
- (void)didReduceButton:(UIButton *)button{
    //字符串转数字   --
//    float floatString = [newString floatValue];
    if (button.superview == self.pendingTextField) {
        
        if ([self.pendingTextField.text isEqualToString:@""]) {
            
        }else{
            
            int floatString = [self.pendingTextField.text intValue];
            
            int newFloat = floatString;
            
            if (newFloat == 10) {
                
                newFloat = 10;
                
                [self showAlertView];
            }else{
                
                newFloat = newFloat - 1;
            }
            
            NSString *stringFloat = [NSString stringWithFormat:@"%d",newFloat];
            
            self.pendingTextField.text = stringFloat;
        }
        
        
        
    }else{
        
        if ([self.stopWinTextField.text isEqualToString:@""]) {
            
        }else{
            
            int floatString = [self.stopWinTextField.text intValue];
            
            int newFloat = floatString;
            
            if (newFloat == 10) {
                
                newFloat = 10;
                
                [self showAlertView];
            }else{
                
                newFloat = newFloat - 1;
            }
            
            NSString *stringFloat = [NSString stringWithFormat:@"%d",newFloat];
            
            self.stopWinTextField.text = stringFloat;
        }
        
        
    }
}


//点击添加按钮
- (void)didAddButton:(UIButton *)button{
    
    if (button.superview == self.pendingTextField) {
        
        if([self.pendingTextField.text isEqualToString:@""]){
            
            self.pendingTextField.text = @"10";
            
        }else{
            
            int floatString = [self.pendingTextField.text intValue];
            
            int newFloat = floatString + 1;
            
            NSString *stringFloat = [NSString stringWithFormat:@"%d",newFloat];
            
            self.pendingTextField.text = stringFloat;
        }
        
        
        
    }else{
        
        if([self.stopWinTextField.text isEqualToString:@""]){
            
            self.stopWinTextField.text = @"10";
            
        }else{
           
            int floatString = [self.stopWinTextField.text intValue];
            
            int newFloat = floatString + 1;
            
            NSString *stringFloat = [NSString stringWithFormat:@"%d",newFloat];
            
            self.stopWinTextField.text = stringFloat;
        }
        
    }
    
}


- (void)showAlertView{
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                   message:@"点数必须大于等于10"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                          handler:^(UIAlertAction * action) {
                                                              //响应事件
//                                                              NSLog(@"action = %@", action);
                                                          }];
    
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
    
}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.pendingTextField resignFirstResponder];
    
    [self.stopWinTextField resignFirstResponder];
}


- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    if([textField.text isEqualToString:@""]){
        
    }else{
        
        int count = [textField.text intValue];
        
        if (count < 10) {
            
            textField.text = @"10";
            
            [self showAlertView];
        }
 
    }
    
    
}


- (void)backToAccountView{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
